package com.rchat.pocmini.activity.setting;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;

import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.bean.AppInfo;
import com.rchat.pocmini.bean2eventbus.BluetoothBean;
import com.rchat.pocmini.bean2eventbus.EventBusAccountBean;
import com.rchat.pocmini.bean2eventbus.LocationReportFreqBean;
import com.rchat.pocmini.bluetooth.BTService;
import com.rchat.pocmini.common.update.AppUpdateGlobal;
import com.rchat.pocmini.common.update.AppUpdateManager;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.IntentKeyGlobal;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.util.PhoneUtil;
import com.rchat.pocmini.util.SPUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by itsdf07 on 2017/8/19.
 */

public class SettingPresenterImpl extends SettingContract.Presenter implements AppUpdateManager.IDownLoadCallback {
    private static final String PLUGINPACKAGE = "com.rchat.remote";

    /**
     * 扫激活码的requestCode
     */
    public static final int REQUEST_CODE_ACTIVATE = 1;

    /**
     * 插件是否正在下载
     */
    private boolean isPluginDownloading = false;

    private String mDownLoadType = AppUpdateGlobal.CheckUpdateModel.CHECK;

    /**
     * 是否有安装插件
     */
    private boolean hasPlugin = false;

    AppInfo mAppInfo;

    @Override
    public void showLocationMenu(final Context context) {
        if (!PhoneUtil.isGpsEnable(mActivity)) {
            Toast.makeText(mActivity, R.string.open_gps, Toast.LENGTH_SHORT).show();
            return;
        }
        int reportFreq = (int) SPUtil.get(context.getApplicationContext(), SPUtil.SPKeyGlobal.KEY_LOCATION_REPORT_FREQ, -1);
        int position = 0;
        switch (reportFreq) {
            case -1:
                position = 0;
                break;
            case 5 * 1000:
                position = 1;
                break;
            case 10 * 1000:
                position = 2;
                break;
            case 30 * 1000:
                position = 3;
                break;
            case 60 * 1000:
                position = 4;
                break;
            case 3 * 60 * 1000:
                position = 5;
                break;
            case 10 * 60 * 1000:
                position = 6;
                break;
        }
        final LocationReportFreqBean bean = new LocationReportFreqBean();
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("请选择位置上报");
        final String[] menu = {"关闭", "5秒", "10秒", "30秒", "1分钟", "3分钟", "10分钟"};
        //    设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉单选框的数据集合
         * 第二个参数代表索引，指定默认哪一个单选框被勾选上，1表示默认'关闭 会被勾选上
         * 第三个参数给每一个单选项绑定一个监听器
         */
        builder.setSingleChoiceItems(menu, position, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                bean.setCurrentEvent(which);
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EventBus.getDefault().post(bean);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();

    }

    @Override
    void activate(String qrCode) {
        mModel.activate(qrCode, PocAccount.getUserId(), new HttpCallbackImpl<BaseBean>() {
            @Override
            public void onStart() {
                mView.showLoading();
            }

            @Override
            public void onSuccess(BaseBean bean) {
                if (mView == null) {
                    return;
                }
                mView.showShortToast(bean.getDesc());
                ALog.d("desc = %s", bean.getDesc());
                EventBusAccountBean eventBusAccountBean = new EventBusAccountBean();
                eventBusAccountBean.setTarget(this.getClass(), GroupsPresenterImpl.class, "onEventBusRequestAccount");
                eventBusAccountBean.setCurrentEvent(EventBusAccountBean.EVENT_ACCOUNT_DATE);
                EventBus.getDefault().post(eventBusAccountBean);

                SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_IS_ENABLEPTT, 1);
                BluetoothBean bluetoothBean = new BluetoothBean();
                bluetoothBean.setCurrentEvent(BluetoothBean.EVENT_ENABLE_PTT);
                bluetoothBean.setTarget(this.getClass(), BTService.class, "onBluetoothEventBus");
                EventBus.getDefault().post(bluetoothBean);
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                if (mView == null) {
                    return;
                }
                mView.showShortToast(bean.getDesc());
                ALog.d("desc = %s", bean.getDesc());
            }

            @Override
            public void onFinish() {
                if (mView == null) {
                    return;
                }
                mView.dismissLoading();
            }
        });
    }

    @Override
    void checkUpdate(String type) {
        if (AppUpdateManager.getInstance(mActivity).isDownLoading()) {
            mView.showShortToast("当前已有下载任务在下载，请稍候在试");
            return;
        }
        mDownLoadType = type;
        if (AppUpdateGlobal.CheckUpdateModel.PLUGIN.equals(type)){
            AppUpdateManager.getInstance(mActivity).setAppinfo(mAppInfo);
        }
        AppUpdateManager.getInstance(mActivity).setDownLoadCallback(this);
        AppUpdateManager.getInstance(mActivity).checkUpdate(type);
    }

    @Override
    void checkPlugin() {

    }

    @Override
    boolean isPluginDownloading() {
        return isPluginDownloading;
    }

    boolean hasPlugin() {
        return hasPlugin;
    }

    /**
     * 检查系统应用程序，添加到应用列表中
     */
    private boolean hasInstallPlugin() {
        ALog.d("mAllApps = %s", getAppInfo().size());
        for (AppInfo appInfo : getAppInfo()) {
            if (null == appInfo) {
                continue;
            }
            ALog.d("versionName = %s，versionCode = %s，包名:%s", appInfo.getVersionName(), appInfo.getVersionCode(), appInfo.getPackageName());
            if (PLUGINPACKAGE.equals(appInfo.getPackageName())) {
                ALog.d("当前设备有安装睿洽插件");
                mAppInfo = appInfo;
                return true;
            }
        }
        return false;
    }

    @Override
    public void onPStart() {
        super.onPStart();
        hasPlugin = hasInstallPlugin();
        if (!hasPlugin) {
            //如果检测不到插件，那么强制关闭进程保活
            SPUtil.put(mActivity, SPUtil.SPKeyGlobal.KEY_BIND_REMOTESERVICE, hasPlugin);
        }
    }

    @Override
    public void onPDestroy() {
        AppUpdateManager.getInstance(mActivity).onCancleDownLoad();
        AppUpdateManager.getInstance(mActivity).setDownLoadCallback(null);
        super.onPDestroy();
    }

    /**
     * 获取已安装应用信息（不包含系统自带）
     */
    private ArrayList<AppInfo> getAppInfo() {
        List<PackageInfo> apps = mActivity.getPackageManager().getInstalledPackages(0);

        ArrayList<AppInfo> infos = new ArrayList<>();

        for (PackageInfo packageInfo : apps) {
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                // 非系统应用
                AppInfo appInfo = new AppInfo();
                appInfo.setAppName(packageInfo.applicationInfo.loadLabel(mActivity.getPackageManager()).toString());
                appInfo.setVersionName(packageInfo.versionName);
                appInfo.setVersionCode(packageInfo.versionCode);
                appInfo.setPackageName(packageInfo.packageName);
                infos.add(appInfo);
            }
        }

        return infos;
    }

    @Override
    public void onProgress(long progress) {
        if (AppUpdateGlobal.CheckUpdateModel.PLUGIN.equals(mDownLoadType)) {
            mView.updateDownloadProgressBar(progress);
        } else {
            mView.updateCheckUpdate((int) progress);
        }

    }

    @Override
    public void onDownLoadFinish(File file) {
        AppUpdateManager.getInstance(mActivity).openApk(mActivity, file);
    }
}
